/*
处理文件上传的路由
 */
const path = require("path");
const multer = require("multer");
const fs = require("fs");

multer.diskStorage({
  destination: "public/upload", //string时,服务启动将会自动创建文件夹
});

const fn_upload = async (ctx, next) => {
  try {
    const file = ctx.request.files.file;
    if (file) {
      ctx.body = {
        data: {
          file: ctx.request.files,
          name: file.name,
          url: `${ctx.origin}/public/upload/${file.name}`,
        },
        message: "上传成功",
        code: 0,
      };
    }
  } catch (error) {
    ctx.body = {
      data: null,
      message: "上传失败" + error,
      code: -1,
    };
  }
};

const fn_base64 = async (ctx, next) => {
  try {
    const imgData = ctx.request.body.img;
    //过滤data:URL
    const base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
    const dataBuffer = new Buffer(base64Data, "base64");
    const fileName = `avatar_${new Date().getTime()}`;
    const res = await new Promise((resolve, reject) => {
      return fs.writeFile(
        path.resolve(__dirname, `../public/upload/${fileName}.png`),
        dataBuffer,
        (err, data) => {
          if (err) {
            reject(err);
          } else {
            resolve({
              data: {
                fileName: `${fileName}.png`,
                url: `${ctx.origin}/public/upload/${fileName}.png`,
              },
              message: "base64上传成功",
              code: 0,
            });
          }
        }
      );
    });
    if (res) {
      ctx.body = res;
    } else {
      ctx.body = {
        data: null,
        message: "上传失败",
        code: -1,
      };
    }
  } catch (error) {
    ctx.body = {
      data: null,
      message: "上传失败" + error,
      code: -1,
    };
  }
};

const fn_delete = async (ctx, next) => {
  try {
    const { name } = ctx.request.body;
    fs.unlink(path.join(dirPath, name), (err) => {
      if (err) {
        ctx.body = {
          data: null,
          message: "删除失败",
          code: -1,
        };
      } else {
        ctx.body = {
          data: null,
          message: "删除成功",
          code: 0,
        };
      }
    });
  } catch (error) {
    ctx.body = {
      message: "删除失败" + error,
      code: -1,
    };
  }
};

module.exports = {
  "POST /manage/img/delete": fn_delete,
  "POST /manage/img/upload": fn_upload,
  "POST /manage/base64/upload": fn_base64,
};
